package com.example.nacosdemo.controller;

import com.example.nacosdemo.service.ConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

import java.util.Map;

/**
 * 高级配置控制器，展示如何在服务层中使用 Nacos 配置
 */
@RestController
@RefreshScope
public class AdvancedConfigController {

    @Autowired
    private ConfigService configService;

    @Value("${spring.application.name}")
    private String serviceName;

    /**
     * 获取完整的配置信息（通过服务层）
     * @return 完整配置信息
     */
    @GetMapping("/api/config")
    public Map<String, Object> getFullConfig() {
        Map<String, Object> result = configService.getConfigInfo();
        result.put("serviceName", serviceName);
        return result;
    }

    /**
     * 获取特定配置项
     * @return 特定配置项
     */
    @GetMapping("/api/config/detail")
    public Map<String, Object> getConfigDetails() {
        Map<String, Object> details = new HashMap<>();
        details.put("message", configService.getMessage());
        details.put("timeout", configService.getTimeout());
        details.put("enabled", configService.isEnabled());
        details.put("tags", configService.getTags());
        return details;
    }

    /**
     * 检查配置状态
     * @return 配置状态
     */
    @GetMapping("/api/config/status")
    public Map<String, Object> checkConfigStatus() {
        Map<String, Object> status = new HashMap<>();
        status.put("serviceName", serviceName);
        status.put("functionEnabled", configService.isEnabled());
        status.put("configurationSource", "Nacos Config Center");
        status.put("dynamicRefresh", "Supported");
        return status;
    }

    /**
     * 获取 Nacos 配置操作指南
     * @return 操作指南
     */
    @GetMapping("/api/config/guide")
    public String getConfigGuide() {
        return "Spring Boot + Nacos 配置中心使用指南：\n" +
               "1. 确保 Nacos 服务器运行在 localhost:8848\n" +
               "2. 访问 http://localhost:8848/nacos 并登录（默认账号密码：nacos/nacos）\n" +
               "3. 在配置管理中创建配置，Data ID: nacos-demo-service.yaml, Group: DEFAULT_GROUP\n" +
               "4. 添加以下示例配置：\n" +
               "   demo.config.message=Hello from Nacos\n" +
               "   demo.config.timeout=60\n" +
               "   demo.config.enabled=true\n" +
               "   demo.config.tags=springboot,nacos,config\n" +
               "5. 发布配置后，访问 /api/config 查看动态刷新效果\n" +
               "6. 修改配置并重新发布，可以看到配置自动刷新（无需重启应用）";
    }
}